#!/bin/sh /etc/rc.common

USE_PROCD=1
START=99

CONF="antiblock"

start_service() {
	config_load "$CONF"

	local _enabled
	config_get_bool _enabled "config" "enabled" "0"
	[ "${_enabled}" -eq "0" ] && return 1

	echo "AntiBlock start"

	local _url
	local _file
	local _listen
	local _DNS
	local _VPN_name
	local _log
	local _stat
	local _output

	config_get _url "config" "url"
	config_get _file "config" "file"

	config_get _listen "config" "listen"
	config_get _DNS "config" "DNS"
	config_get _VPN_name "config" "VPN_name"

	config_get_bool _log "config" "log" "0"
	config_get_bool _stat "config" "stat" "0"
	config_get _output "config" "output"

	procd_open_instance "$CONF"

	procd_set_param command "/usr/bin/antiblock"
	procd_set_param stdout 1
	procd_set_param stderr 1

	[ -n "${_url}" ] && procd_append_param command -url "${_url}"
	[ -n "${_file}" ] && procd_append_param command -file "${_file}"

	if [ -n "${_listen}" ]; then
		local listen_IP="$(echo "${_listen}" | cut -d ':' -f1)"
		local listen_port="$(echo "${_listen}" | cut -d ':' -f2)"
		uci -q set dhcp.@dnsmasq[0].noresolv="1"
		uci -q delete dhcp.@dnsmasq[0].server
		uci -q add_list dhcp.@dnsmasq[0].server="$listen_IP#$listen_port"

		procd_append_param command -listen "${_listen}"
	fi
	[ -n "${_DNS}" ] && procd_append_param command -DNS "${_DNS}"
	if [ -n "${_VPN_name}" ]; then
		local gateway="$(ip r | grep -v via | grep "dev ${_VPN_name} " | grep src | awk '{print $NF}')"
		procd_append_param command -gateway "$gateway"
	fi

	[ "${_log}" -ne "0" ] && procd_append_param command -log
	[ "${_stat}" -ne "0" ] && procd_append_param command -stat
	if [ -n "${_output}" ]; then
		mkdir -p "${_output}"
		procd_append_param command -output "${_output}"
	fi

	procd_close_instance

	/etc/init.d/dnsmasq restart >/dev/null 2>&1
}

stop_service() {
	echo "AntiBlock stop"

	uci -q revert dhcp.@dnsmasq[0]

	/etc/init.d/dnsmasq restart >/dev/null 2>&1
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
